<?php
/**
 * Created by PhpStorm.
 * User: caoSan
 * Date: 2015/11/13
 * Time: 17:26
 */
//允许调用
if(!defined('ALLOW')) {
    exit('非法调用!');
}

include "./data/common.inc.php";
//创建对象并打开连接，最后一个参数是选择的数据库名称
$mysqli = new mysqli($cfg_dbhost,$cfg_dbuser,$cfg_dbpwd,$cfg_dbname);
//检查连接是否成功
if (mysqli_connect_errno()){
    //注意mysqli_connect_error()新特性
    die('数据库连接失败!'). mysqli_connect_error();
}
if (!$mysqli->set_charset("utf8")) {
    printf("字符集设置错误\n", $mysqli->error);
}

/**
 * 分页
 */
function _page($_sql,$_size) {
    global $mysqli;
    //将里面的所有变量取出来，外部可以访问
    global $_page,$_pagesize,$_pagenum,$_pageabsolute,$_num;
    if (isset($_GET['page'])) {
        $_page = $_GET['page'];
        if (empty($_page) || $_page < 0 || !is_numeric($_page)) {
            $_page = 1;
        } else {
            $_page = intval($_page);
        }
    } else {
        $_page = 1;
    }
    $_pagesize = $_size;
    $_result = mysqli_query($mysqli, $_sql);
    $_num = mysqli_num_rows($_result);
    if ($_num == 0) {
        $_pageabsolute = 1;
    } else {
        $_pageabsolute = ceil($_num / $_pagesize);
    }
    if ($_page > $_pageabsolute) {
        $_page = $_pageabsolute;
    }
    $_pagenum = ($_page - 1) * $_pagesize;
}
function _paging() {
    global $_page,$_pageabsolute,$_num;
    echo '<div class="pagelist">';
    echo '<ul>';
    for ($i=0;$i<$_pageabsolute;$i++) {
        if ($_page == ($i+1)) {
            echo '<li class="thisclass"><a href="?action=list&page='.($i+1).'">'.($i+1).'</a></li>';
        } else {
            echo '<li><a href="?action=list&page='.($i+1).'">'.($i+1).'</a></li>';
        }
    }
    echo '</ul>';
    echo '</div>';
}

//分页模块
global $_pagesize,$_pagenum;
_page("SELECT id FROM dede_msg WHERE reply is not null", 10);   //第一个参数获取总条数，第二个参数，指定每页多少条

$sql = "SELECT username,content,time,reply,replytime FROM dede_msg WHERE reply is not null ORDER BY time DESC LIMIT $_pagenum,$_pagesize";
//执行sql语句，完全面向对象的
$result = $mysqli->query($sql);
$html = '';
$html .= '<ul class="msglist">';
while($row = $result->fetch_assoc()) {
    $html .= '<li>';
    $html .= '<div class="msg_a">';
    $html .= '<span>'.$row["username"].'</span> 于 <span>'.$row["time"].'</span> 发表';
    $html .= '</div>';
    $html .= '<div class="msg_b">';
    $html .= '提问：'.$row["content"].'';
    $html .= '</div>';
    $html .= '<div class="msg_c">';
    $html .= '回复：'.$row["reply"].'';
    $html .= '</div>';
    $html .= '</li>';
}
$html .= '</ul>';
echo $html;
_paging();

$mysqli->close();